package com.nbsaas.boot.resource;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.nbsaas.boot.config.ext.apis.ConfigExtApi;
import com.nbsaas.boot.rest.response.ResponseObject;
import com.nbsaas.boot.storage.ext.apis.OssApi;
import com.nbsaas.boot.storage.ext.domain.config.AliOssConfig;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.net.URL;
import java.util.Date;

@Service
public class OssResource implements OssApi {

    @Resource
    private ConfigExtApi configExtApi;


    @Override
    public ResponseObject<String> url(String key) {
        ResponseObject<String> result = new ResponseObject<>();

        // 检查文件是否为空  @RequestParam("file")
        if (key==null) {
            result.setCode(501);
            result.setMsg("请选择一个文件进行上传");
            return result;
        }
        ResponseObject<AliOssConfig> res = configExtApi.info(AliOssConfig.class);
        if (res.getCode() != 200) {
            result.setCode(502);
            result.setMsg("你没有配置上传信息");
            return result;
        }
        AliOssConfig config= res.getData();
        OSS ossClient = new OSSClientBuilder().build(config.getEndpoint(), config.getAccessKeyId(), config.getAccessKeySecret());
        Integer accessControl = config.getAccessControl();
        if (accessControl==null){
            accessControl=2;
        }
        if (accessControl==1){
            try {
                // Set the validity period of the signed URL to 3,600 seconds (1 hour).
                Date expiration = new Date(new Date().getTime() + 3600 * 1000);
                // Generate the signed URL that allows HTTP GET requests. Visitors can enter the URL in a browser to access specified OSS resources.
                URL url = ossClient.generatePresignedUrl(config.getBucketName(), key, expiration);
                result.setData(url.toString());
            } catch (Throwable e) {
                result.setCode(501);
                result.setMsg("上传文件失败");
            } finally {
                ossClient.shutdown();
            }
        }else{
            result.setData(config.getDomain()+key);
        }

        return result;
    }
}
